<template>
  <div class="zy-content">

    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{$t('公司')}}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.companyCode"
                  label-in-value
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
                  @on-change="paramsCompanySelectChange"
              >
                <Option v-for="(item, index) of companyList"
                        :value="item.code"
                        :label="item.name"
                        :key="index">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('厂区')}}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.factoryCode"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
                  @on-change="paramsFactorySelectChange"
              >
                <Option v-for="(item, index) of factoryLists"
                        :value="item.code"
                        :label="item.name"
                        :key="index">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('bigScreen.Line')}}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.lineCode"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option v-for="(item, index) of productionLineLists"
                        :value="item.code"
                        :label="item.name"
                        :key="index">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">E-ORDER</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.dataSource"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option :value="1" :label="$t('common.Yes')"></Option>
                <Option :value="0" :label="$t('common.No')"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="changeNum()">{{ $t('common.Query') }}</Button>
              <Button
                  class="reset-btn"
                  @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">


        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="addClickinfo" v-has="'organizationParamAdd'">{{ $t('common.New') }}</Button>
          <Button @click="getTableColumns(columns)">
              {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
          </Button>
      </div>

      <div class="tableContent">
        <Table
            class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList"
            :data="dataSource"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="yearInventoryDate">
                    <span v-if="row.yearInventoryStartDate && row.yearInventoryEndDate">
                        {{ row.yearInventoryStartDate }} ~ {{ row.yearInventoryEndDate }}
                    </span>
          </template>

          <template slot-scope="{ row }" slot="dataSource">
                    <span>
                        {{ row.dataSource === 0 ? $t('common.No') : $t('common.Yes') }}
                    </span>
          </template>

          <template slot-scope="{ row }" slot="action">
            <template v-if="Number(row.dataSource) === 0">
                     <span class="operationBtn"
                           v-has="'organizationParamEdit'"
                           @click="addClickinfo(row)">
                        <i class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}
                    </span>
            </template>
            <template v-if="Number(row.dataSource) === 0">
                    <span
                        class="operationBtn"
                        v-has="'organizationParamDel'"
                        @click="(deleteModal = true), (deleteIds = [row.id])"
                    ><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
            </template>
          </template>
        </Table>
      </div>

      <div class="pageWrap mt16">
        <pageLeftTitle :total="total"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="$variable.pageSizes"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
    <Modal :mask-closable="false" v-model="addModal" :title="addtitle" class="modal-content-layout">
      <Form
          ref="formValidate"
          class="formList"
          :model="formItem"
          :rules="rules"
          label-position="top"
      >
        <FormItem :label="`${$t('common.company')}`" prop="companyCode">
          <Select
              v-model="formItem.companyCode"
              label-in-value
              filterable
              clearable
              @on-change="companySelectChange"
              :placeholder="`${$t('common.selectInfo')}`"
          >
            <Option v-for="(item, index) of companyList"
                    :value="item.code"
                    :label="item.name"
                    :key="index">
            </Option>
            >
          </Select>
        </FormItem>
        <FormItem :label="$t('厂区')" prop="factoryCode">
          <Select
              v-model="formItem.factoryCode"
              filterable
              clearable
              :placeholder="`${$t('common.selectInfo')}`"
              @on-change="factorySelectChange"
          >
            <Option v-for="(item, index) of factoryList"
                    :value="item.code"
                    :label="item.name"
                    :key="index">
            </Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('bigScreen.Line')">
          <Select
              v-model="formItem.lineCode"
              filterable
              clearable
              :placeholder="`${$t('common.selectInfo')}`"
          >
            <Option v-for="(item, index) of productionLineList"
                    :value="item.code"
                    :label="item.name"
                    :key="index">
            </Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('年终盘点时间')" prop="yearInventoryDate">
          <DatePicker v-model="formItem.yearInventoryDate"
                      type="daterange"
                      format="yyyy-MM-dd"
                      placement="bottom-end"
                      :placeholder="`${$t('common.selectInfo')}`"/>
        </FormItem>
        <FormItem :label="$t('目标OEE')" prop="targetOee">
          <Input
              :placeholder="`${$t('common.inputInfo')}`"
              type="text"
              v-model="formItem.targetOee"
          ></Input>
        </FormItem>
        <FormItem :label="$t('最大OEE')" prop="maxOee">
          <Input
              :placeholder="`${$t('common.inputInfo')}`"
              type="number"
              v-model="formItem.maxOee"
          ></Input>
        </FormItem>
        <FormItem :label="$t('最小OEE')" prop="minOee">
          <Input
              :placeholder="`${$t('common.inputInfo')}`"
              type="number"
              v-model="formItem.minOee"
          ></Input>
        </FormItem>
        <FormItem :label="$t('瓶颈工站')" prop="bottleneckWorkStation">
          <Input
              :placeholder="`${$t('common.inputInfo')}`"
              type="text"
              v-model="formItem.bottleneckWorkStation"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="addModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="handleSubmit('formValidate')">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>

    <Modal :mask-closable="false" v-model="deleteModal" :title="$t('common.Delete')"
           class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.confirmDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="handleDelete">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <importExcelModal
        :importExcelStateF="importExcelState"
        v-if="importExcelState"
        @importExcelChange="importExcelChange"
    ></importExcelModal>
  </div>
</template>

<script>
import importExcelModal from "@/components/importExcel.vue";
import {findOrgByLevel} from "@/api";
import {queryPage, add, edit, deleted} from "@/api/system/organizationParam.js";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "faultClassify",
  components: {importExcelModal},
    mixins:[toggleTableOperation],
  data() {
    return {
      searchParams: {},
      faultName: '',
      faultCode: '',
      total: 0, // 总数
      pageNum: 1, // 页数
      pageSize: 10, // 每页的个数
      pageSizeOption: [10, 20, 30],
      addModal: false, // 新增弹窗
      addtitle: "", // 新增/编辑 标题
      formItem: {},
      rules: { // 校验规则
        factoryCode: [
          {required: true, type: 'string', message: this.$t('common.selectInfo'), trigger: "blur"},
        ],
        companyCode: [
          {required: true, type: 'string', message: this.$t('common.selectInfo'), trigger: "blur"},
        ]
      },
      deleteModal: false, // 删除弹窗
      deleteIds: [], // 删除Id
      importExcelState: false, // 导入弹窗
      checkBtnPermission: {}, // 按钮权限
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: `${this.$t('common.company')}`,
          key: "companyName",
          align: "center",
          minWidth: 150,
            resizable: true
        },
        {
          // title: "厂区",
          title: `${this.$t('厂区')}`,
          key: "factoryName",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: "产线",
          title: `${this.$t('bigScreen.Line')}`,
          key: "lineName",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: "目标OEE",
          title: `${this.$t('目标OEE')}`,
          key: "targetOee",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: "最大OEE",
          title: `${this.$t('最大OEE')}`,
          key: "maxOee",
          align: "center",
          minWidth: 150,
            resizable: true
        },
        {
          // title: "最小OEE",
          title: `${this.$t('最小OEE')}`,
          key: "minOee",
          align: "center",
          minWidth: 150,
            resizable: true
        },
        {
          // title: "年终盘点时间",
          title: `${this.$t('年终盘点时间')}`,
          slot: "yearInventoryDate",
          align: "center",
          minWidth: 200,
            resizable: true
        },
        {
          // title: "月计划产量",
          title: `${this.$t('月计划产量')}`,
          key: "monthPlanYield",
          align: "center",
          minWidth: 200,
            resizable: true
        },
        {
          // title: "年计划产量",
          title: `${this.$t('年计划产量')}`,
          key: "yearPlanYield",
          align: "center",
          minWidth: 200,
            resizable: true
        },
        {
          // title: "年",
          title: `${this.$t('年')}`,
          key: "year",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: "年月",
          title: `${this.$t('年月')}`,
          key: "yearMonth",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: "更新时间",
          title: `${this.$t('更新时间')}`,
          key: "updateTime",
          align: "center",
          minWidth: 180,
            resizable: true
        },
        {
          title: "E-ORDER",
          slot: "dataSource",
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          minWidth: 200,
          fixed: "right",
          slot: "action",
          align: "center",
        },
      ],
      dataSource: [],
      companyList: [],
      factoryList: [],
      productionLineList: [],
      productionLineLists: [],
      factoryLists: [],
    };
  },
  created() {

      this.getTableColumnsWidth(this.columns)

    this.getCompanyList();
    // this.getFactoryList();
    this.searchList();
  },
  methods: {
    addClickinfo(row = {}) {
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`
        this.formItem = {
          companyCode: row.companyCode,
          companyName: row.companyName,
          factoryCode: row.factoryCode,
          lineCode: row.lineCode,
          yearInventoryDate: [row.yearInventoryStartDate, row.yearInventoryEndDate],
          targetOee: row.targetOee,
          maxOee: row.maxOee,
          minOee: row.minOee,
          bottleneckWorkStation: row.bottleneckWorkStation,
          dataSource: row.dataSource,
          id: row.id,
        };
        this.getFactoryList(row.companyCode, 'factoryList', () => {
          this.getProductionLineList(this.formItem.factoryCode, 'productionLineList')
        });

      } else {
        this.addtitle = `${this.$t('common.New')}`
        this.formItem = {}
        this.$refs['formValidate'].resetFields()
      }
      this.addModal = true;
    },
    // 新增提交
    handleSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          console.log(!this.formItem.yearInventoryDate);
          console.log(this.formItem.yearInventoryDate);
          console.log((!this.formItem.yearInventoryDate ||
              (!this.formItem.yearInventoryDate[0] &&
                  !this.formItem.yearInventoryDate[1])));
          console.log(!this.formItem.targetOee);
          console.log(!this.formItem.maxOee);
          console.log(!this.formItem.minOee);
          console.log(!this.formItem.bottleneckWorkStation);

          if ((!this.formItem.yearInventoryDate ||
                  (!this.formItem.yearInventoryDate[0] &&
                      !this.formItem.yearInventoryDate[1])) &&
              !this.formItem.targetOee &&
              !this.formItem.maxOee &&
              !this.formItem.minOee &&
              !this.formItem.bottleneckWorkStation) {

            this.$Message.warning({
              content: this.$t('参数必须填写一项'),
              duration: 6,
              closable: true,
            });
            return;
          }
          if (this.formItem.yearInventoryDate) {
            this.formItem.yearInventoryStartDate = this.formatDate(this.formItem.yearInventoryDate[0]);
            this.formItem.yearInventoryEndDate = this.formatDate(this.formItem.yearInventoryDate[1]);
          }

          if (this.formItem.id) {
            this.handleEdit();
          } else {
            this.handleAdd();
          }
        }
      });
    },
    formatDate(format) {
      if (!format) {
        return null;
      }
      let date = new Date(format);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      return year + "-" + month + "-" + day;
    },
    handleAdd() {
      add(this.formItem).then((res) => {
        if (res.code === 200) {
          this.addModal = false;
          this.$Message.success(res.msg);
          this.changeNum();
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      })
    },
    handleEdit() {
      edit(this.formItem).then((res) => {
        if (res.code === 200) {
          this.addModal = false;
          this.$Message.success(res.msg);
          this.changeNum();
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      })
    },
    // 删除操作
    handleDelete() {
      let params = {
        id: this.deleteIds[0]
      }
      deleted(params).then((res) => {
        if (res.code === 200) {
          this.deleteModal = false;
          this.$Message.success(res.msg);
          this.changeNum();
          this.deleteIds = []
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    reset (){
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      };
      queryPage(params).then((res) => {
        if (res.code === 200) {

          res.data.list.forEach(e => {
            e.yearInventoryDate = [e.yearInventoryStartDate, e.yearInventoryEndDate];
          });

          this.dataSource = res.data.list;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    onSelectChange(selection) {
      this.deleteIds = selection.map((item) => item.id);
    },
    //获取公司
    getCompanyList() {
      findOrgByLevel({level: 2}).then(res => {
        if (res.code === 200) {
          this.companyList = res.data
        } else {
          this.companyList = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getFactoryList(code, listKey, callback) {

      const obj = this.companyList.find(item => item.code === code)
      let params = {
        level: 3,
        parentId: obj.id
      }
      findOrgByLevel(params).then(res => {
        if (res.code === 200) {
          this[listKey] = res.data
          if (typeof callback === 'function')
            callback()
        } else {
          this[listKey] = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getProductionLineList(floorCode, listKey) {
      const obj = (listKey === 'productionLineList' ? this.factoryList : this.factoryLists).find(item => item.code === floorCode)
      if (!obj.id) {
        this[listKey] = [];
        return;
      }
      let params = {
        level: 4,
        parentId: obj.id
      }
      findOrgByLevel(params).then(res => {
        if (res.code === 200) {
          this[listKey] = res.data
        } else {
          this[listKey] = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.loading = false
      })
    },
    factorySelectChange() {
      if (this.formItem.factoryCode) {
        this.getProductionLineList(this.formItem.factoryCode, 'productionLineList');
      } else {
        this.productionLineList = []
        this.formItem.lineCode = ''
      }
    },
    paramsFactorySelectChange() {
      if (this.searchParams.factoryCode) {
        this.getProductionLineList(this.searchParams.factoryCode, 'productionLineLists');
      } else {
        this.productionLineLists = []
        this.searchParams.lineCode = ''
      }
    },
    paramsCompanySelectChange(event) {
      if (this.searchParams.companyCode) {
        this.searchParams.companyName = event.label;
        this.getFactoryList(this.searchParams.companyCode, 'factoryLists');
      } else {
        this.factoryLists = []
        this.searchParams.factoryCode = ''
      }
    },
    companySelectChange(event) {
      if (this.formItem.companyCode) {
        this.getFactoryList(this.formItem.companyCode, 'factoryList');
        this.formItem.companyName = event.label;
      } else {
        this.factoryList = []
        this.formItem.factoryCode = ''
      }
    }
  },
};
</script>

<style scoped lang="scss">
</style>


